{% extends "templates/web.html" %}

{% block page_content %}
<style>
/* Flowa Admin 设计系统样式 */
:root {
  /* 颜色系统 */
  --primary: 212 100% 45%;
  --primary-foreground: 0 0% 98%;
  --background: 0 0% 100%;
  --foreground: 210 6% 21%;
  --card: 0 0% 100%;
  --card-foreground: 222.2 84% 4.9%;
  --border: 240 5.9% 90%;
  --muted: 240 4.8% 95.9%;
  --muted-foreground: 240 3.8% 46.1%;
  --success: 144 57% 58%;
  --success-foreground: 0 0% 98%;
  --warning: 42 84% 61%;
  --warning-foreground: 0 0% 98%;
  --destructive: 359.33 100% 65.1%;
  --destructive-foreground: 0 0% 98%;
  --radius: 0.5rem;
  
  /* 字体系统 */
  --font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif;
  --font-size-base: 16px;
}

/* 全局重置 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: var(--font-family);
  font-size: var(--font-size-base);
  line-height: 1.5;
  color: hsl(var(--foreground));
  background-color: hsl(var(--background));
}

/* 主容器 */
.flowa-container {
  min-height: 100vh;
  background: linear-gradient(135deg, hsl(var(--background)) 0%, hsl(var(--muted)) 100%);
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.flowa-header {
  background: hsl(var(--card));
  border-bottom: 1px solid hsl(var(--border));
  padding: 1rem 2rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.flowa-header h1 {
  font-size: 1.5rem;
  font-weight: 600;
  color: hsl(var(--foreground));
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.flowa-header .logo {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, hsl(var(--primary)), hsl(var(--success)));
  border-radius: var(--radius);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
}

/* 主内容区域 */
.flowa-main {
  flex: 1;
  padding: 2rem;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
}

/* 搜索卡片 */
.flowa-search-card {
  background: hsl(var(--card));
  border: 1px solid hsl(var(--border));
  border-radius: calc(var(--radius) * 2);
  padding: 2rem;
  margin-bottom: 2rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.flowa-search-card h2 {
  font-size: 1.25rem;
  font-weight: 600;
  color: hsl(var(--foreground));
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.flowa-search-form {
  display: flex;
  gap: 1rem;
  align-items: end;
}

.flowa-input-group {
  flex: 1;
}

.flowa-input-group label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  color: hsl(var(--foreground));
  margin-bottom: 0.5rem;
}

.flowa-input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 1px solid hsl(var(--border));
  border-radius: var(--radius);
  font-size: 1rem;
  transition: all 0.2s;
  background: hsl(var(--background));
  color: hsl(var(--foreground));
}

.flowa-input:focus {
  outline: none;
  border-color: hsl(var(--primary));
  box-shadow: 0 0 0 3px hsl(var(--primary) / 0.1);
}

.flowa-input::placeholder {
  color: hsl(var(--muted-foreground));
}

.flowa-button {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: var(--radius);
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  white-space: nowrap;
}

.flowa-button-primary {
  background: hsl(var(--primary));
  color: hsl(var(--primary-foreground));
}

.flowa-button-primary:hover {
  background: hsl(var(--primary) / 0.9);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px hsl(var(--primary) / 0.3);
}

.flowa-button-secondary {
  background: hsl(var(--muted));
  color: hsl(var(--muted-foreground));
  border: 1px solid hsl(var(--border));
}

.flowa-button-secondary:hover {
  background: hsl(var(--muted) / 0.8);
}

/* 状态筛选卡片 */
.flowa-filter-card {
  background: hsl(var(--card));
  border: 1px solid hsl(var(--border));
  border-radius: calc(var(--radius) * 2);
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.flowa-filter-tabs {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.flowa-filter-tab {
  padding: 0.5rem 1rem;
  border-radius: calc(var(--radius) * 3);
  cursor: pointer;
  transition: all 0.2s;
  font-size: 0.875rem;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  border: 1px solid transparent;
}

.flowa-filter-tab.active {
  background: hsl(var(--primary));
  color: hsl(var(--primary-foreground));
  border-color: hsl(var(--primary));
}

.flowa-filter-tab:not(.active) {
  background: hsl(var(--muted));
  color: hsl(var(--muted-foreground));
  border-color: hsl(var(--border));
}

.flowa-filter-tab:not(.active):hover {
  background: hsl(var(--muted) / 0.8);
  border-color: hsl(var(--primary) / 0.5);
}

/* 结果表格卡片 */
.flowa-table-card {
  background: hsl(var(--card));
  border: 1px solid hsl(var(--border));
  border-radius: calc(var(--radius) * 2);
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.flowa-table {
  width: 100%;
  border-collapse: collapse;
}

.flowa-table thead {
  background: hsl(var(--muted));
  border-bottom: 1px solid hsl(var(--border));
}

.flowa-table th {
  padding: 1rem;
  text-align: left;
  font-weight: 600;
  font-size: 0.875rem;
  color: hsl(var(--foreground));
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.flowa-table tbody tr {
  border-bottom: 1px solid hsl(var(--border));
  transition: all 0.2s;
  cursor: pointer;
}

.flowa-table tbody tr:hover {
  background: hsl(var(--muted) / 0.5);
}

.flowa-table tbody tr.selected {
  background: hsl(var(--primary) / 0.1);
  border-left: 4px solid hsl(var(--primary));
}

.flowa-table td {
  padding: 1rem;
  vertical-align: top;
}

/* 状态徽章 */
.flowa-status-badge {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.25rem 0.75rem;
  border-radius: calc(var(--radius) * 3);
  font-size: 0.75rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.flowa-status-badge.delivered {
  background: hsl(var(--success) / 0.1);
  color: hsl(var(--success));
  border: 1px solid hsl(var(--success) / 0.3);
}

.flowa-status-badge.processing {
  background: hsl(var(--warning) / 0.1);
  color: hsl(var(--warning));
  border: 1px solid hsl(var(--warning) / 0.3);
}

.flowa-status-badge.transit {
  background: hsl(var(--primary) / 0.1);
  color: hsl(var(--primary));
  border: 1px solid hsl(var(--primary) / 0.3);
}

.flowa-status-badge.not-found {
  background: hsl(var(--destructive) / 0.1);
  color: hsl(var(--destructive));
  border: 1px solid hsl(var(--destructive) / 0.3);
}

.flowa-status-badge.alert {
  background: hsl(var(--warning) / 0.1);
  color: hsl(var(--warning));
  border: 1px solid hsl(var(--warning) / 0.3);
}

.flowa-status-badge.returned {
  background: hsl(var(--muted));
  color: hsl(var(--muted-foreground));
  border: 1px solid hsl(var(--border));
}

/* 跟踪号样式 */
.flowa-tracking-number {
  font-weight: 600;
  color: hsl(var(--primary));
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 0.875rem;
}

.flowa-tracking-route {
  font-size: 0.75rem;
  color: hsl(var(--muted-foreground));
  margin-top: 0.25rem;
}

/* 详细信息展开 */
.flowa-detail-row {
  display: none;
  background: hsl(var(--muted) / 0.3);
  border-top: 1px solid hsl(var(--border));
}

.flowa-detail-row.expanded {
  display: table-row;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    max-height: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    max-height: 500px;
    transform: translateY(0);
  }
}

.flowa-detail-content {
  padding: 2rem;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 2rem;
}

.flowa-timeline-section h4 {
  font-size: 1rem;
  font-weight: 600;
  color: hsl(var(--foreground));
  margin-bottom: 1rem;
}

.flowa-timeline-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 1rem;
  position: relative;
  padding-left: 1.5rem;
}

.flowa-timeline-item:not(:last-child)::before {
  content: '';
  position: absolute;
  left: 0.5rem;
  top: 1.25rem;
  bottom: -1rem;
  width: 2px;
  background: hsl(var(--border));
}

.flowa-timeline-item::after {
  content: '';
  position: absolute;
  left: 0.25rem;
  top: 1rem;
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 50%;
  background: hsl(var(--primary));
}

.flowa-timeline-time {
  font-size: 0.75rem;
  color: hsl(var(--muted-foreground));
  margin-bottom: 0.25rem;
}

.flowa-timeline-event {
  font-size: 0.875rem;
  color: hsl(var(--foreground));
  font-weight: 500;
}

.flowa-timeline-location {
  font-size: 0.75rem;
  color: hsl(var(--muted-foreground));
  margin-top: 0.25rem;
}

/* 侧边栏信息 */
.flowa-sidebar-section h4 {
  font-size: 1rem;
  font-weight: 600;
  color: hsl(var(--foreground));
  margin-bottom: 1rem;
}

.flowa-info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.75rem;
  padding-bottom: 0.75rem;
  border-bottom: 1px solid hsl(var(--border));
}

.flowa-info-row:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.flowa-info-label {
  color: hsl(var(--muted-foreground));
  font-size: 0.875rem;
}

.flowa-info-value {
  color: hsl(var(--foreground));
  font-size: 0.875rem;
  font-weight: 500;
}

.flowa-info-value a {
  color: hsl(var(--primary));
  text-decoration: none;
}

.flowa-info-value a:hover {
  text-decoration: underline;
}

/* 加载和错误状态 */
.flowa-loading {
  text-align: center;
  padding: 3rem;
  color: hsl(var(--muted-foreground));
}

.flowa-error {
  background: hsl(var(--destructive) / 0.1);
  color: hsl(var(--destructive));
  padding: 1rem;
  border-radius: var(--radius);
  margin: 1rem 0;
  border: 1px solid hsl(var(--destructive) / 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .flowa-main {
    padding: 1rem;
  }
  
  .flowa-search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .flowa-filter-tabs {
    flex-direction: column;
  }
  
  .flowa-detail-content {
    grid-template-columns: 1fr;
  }
  
  .flowa-table {
    font-size: 0.875rem;
  }
  
  .flowa-table th,
  .flowa-table td {
    padding: 0.75rem 0.5rem;
  }
}

/* 空状态 */
.flowa-empty-state {
  text-align: center;
  padding: 3rem;
  color: hsl(var(--muted-foreground));
}

.flowa-empty-state h3 {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: hsl(var(--foreground));
}

.flowa-empty-state p {
  font-size: 0.875rem;
  margin-bottom: 1.5rem;
}

/* 工具提示 */
.flowa-tooltip {
  position: relative;
  display: inline-block;
}

.flowa-tooltip .flowa-tooltip-text {
  visibility: hidden;
  width: 200px;
  background-color: hsl(var(--foreground));
  color: hsl(var(--background));
  text-align: center;
  border-radius: var(--radius);
  padding: 0.5rem;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -100px;
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 0.75rem;
}

.flowa-tooltip:hover .flowa-tooltip-text {
  visibility: visible;
  opacity: 1;
}
</style>

<div class="flowa-container">
  <!-- 顶部导航栏 -->
  <header class="flowa-header">
    <h1>
      <div class="logo">F</div>
      Flowa TMS 跟踪系统
    </h1>
    <div class="flowa-tooltip">
      <span class="flowa-tooltip-text">基于 Flowa Admin 设计系统</span>
      <span style="color: hsl(var(--muted-foreground)); font-size: 0.875rem;">v2.0</span>
    </div>
  </header>

  <!-- 主内容区域 -->
  <main class="flowa-main">
    <!-- 搜索卡片 -->
    <div class="flowa-search-card">
      <h2>
        <span>🔍</span>
        包裹跟踪查询
      </h2>
      <form class="flowa-search-form" id="trackingForm">
        <div class="flowa-input-group">
          <label for="trackingInput">跟踪号码</label>
          <input 
            type="text" 
            id="trackingInput" 
            class="flowa-input"
            placeholder="输入跟踪号，多个号码用分号分隔"
            value=""
          >
        </div>
        <button type="submit" class="flowa-button flowa-button-primary" id="trackBtn">
          <span>🚀</span>
          开始跟踪
        </button>
      </form>
    </div>

    <!-- 状态筛选卡片 -->
    <div class="flowa-filter-card">
      <div class="flowa-filter-tabs">
        <div class="flowa-filter-tab active" data-status="all">
          <span>📦</span>
          <span>全部 (<span id="allCount">0</span>)</span>
        </div>
        <div class="flowa-filter-tab" data-status="processing">
          <span>⚙️</span>
          <span>处理中 (<span id="processingCount">0</span>)</span>
        </div>
        <div class="flowa-filter-tab" data-status="transit">
          <span>✈️</span>
          <span>运输中 (<span id="transitCount">0</span>)</span>
        </div>
        <div class="flowa-filter-tab" data-status="delivered">
          <span>✅</span>
          <span>已送达 (<span id="deliveredCount">0</span>)</span>
        </div>
        <div class="flowa-filter-tab" data-status="not-found">
          <span>❌</span>
          <span>未找到 (<span id="notFoundCount">0</span>)</span>
        </div>
        <div class="flowa-filter-tab" data-status="alert">
          <span>⚠️</span>
          <span>异常 (<span id="alertCount">0</span>)</span>
        </div>
        <div class="flowa-filter-tab" data-status="returned">
          <span>🔄</span>
          <span>已退回 (<span id="returnedCount">0</span>)</span>
        </div>
      </div>
    </div>

    <!-- 结果表格卡片 -->
    <div id="trackingResults" class="flowa-table-card" style="display: none;">
      <table class="flowa-table">
        <thead>
          <tr>
            <th>跟踪号码</th>
            <th>配送状态</th>
            <th>最后一公里</th>
            <th>订单号</th>
            <th>最新事件</th>
          </tr>
        </thead>
        <tbody id="trackingTableBody">
          <!-- 跟踪结果将通过JavaScript动态生成 -->
        </tbody>
      </table>
    </div>

    <!-- 加载状态 -->
    <div id="loadingState" class="flowa-loading" style="display: none;">
      <h3>正在查询跟踪信息...</h3>
      <p>请稍候，我们正在为您获取最新的包裹状态</p>
    </div>

    <!-- 错误状态 -->
    <div id="errorState" class="flowa-error" style="display: none;">
      <p id="errorMessage">查询失败，请稍后重试</p>
    </div>

    <!-- 空状态 -->
    <div id="emptyState" class="flowa-empty-state" style="display: none;">
      <h3>暂无跟踪数据</h3>
      <p>请输入跟踪号码开始查询</p>
    </div>
  </main>
</div>

<script>
// 全局变量
let trackingData = [];
let currentFilter = 'all';

// 初始化跟踪页面
document.addEventListener('DOMContentLoaded', function() {
  console.log('===== Flowa TMS跟踪页面初始化开始 =====');
  console.log('初始化时间:', new Date().toLocaleString());
  console.log('版本: v2.0 - Flowa Admin 设计系统');
  console.log('API集成: 已连接云途物流API');
  
  // 清除所有测试数据
  trackingData = [];
  clearAllResults();
  
  bindEvents();
  console.log('===== Flowa TMS跟踪页面初始化完成 =====');
  console.log('页面已准备就绪，可以开始真实跟踪查询');
});

// 清除所有结果显示
function clearAllResults() {
  // 隐藏结果表格
  const resultsDiv = document.getElementById('trackingResults');
  if (resultsDiv) {
    resultsDiv.style.display = 'none';
  }
  
  // 清空表格内容
  const tableBody = document.getElementById('trackingTableBody');
  if (tableBody) {
    tableBody.innerHTML = '';
  }
  
  // 重置状态计数
  updateStatusCounts();
}

// 绑定事件
function bindEvents() {
  // 跟踪表单提交
  const trackingForm = document.getElementById('trackingForm');
  if (trackingForm) {
    trackingForm.addEventListener('submit', function(e) {
      e.preventDefault();
      handleTrack();
    });
  }

  // 跟踪输入框回车键
  const trackingInput = document.getElementById('trackingInput');
  if (trackingInput) {
    trackingInput.addEventListener('keypress', function(e) {
      if (e.key === 'Enter') {
        handleTrack();
      }
    });
  }

  // 状态筛选标签
  const filterTabs = document.querySelectorAll('.flowa-filter-tab');
  filterTabs.forEach(tab => {
    tab.addEventListener('click', function() {
      const status = this.dataset.status;
      setActiveFilter(status);
      filterTrackingResults(status);
    });
  });
}

// 处理多个跟踪号查询
async function handleTrack() {
  const input = document.getElementById('trackingInput').value.trim();

  if (!input) {
    showError('请输入跟踪号');
    return;
  }

  // 解析多个跟踪号（用分号分隔）
  const trackingNumbers = input.split(';').map(num => num.trim()).filter(num => num.length > 0);
  
  if (trackingNumbers.length === 0) {
    showError('请输入有效的跟踪号');
    return;
  }

  // 显示加载状态
  showLoading();

  try {
    // 调用云途API获取跟踪信息
    const apiResponse = await frappe.call({
      method: 'upsystem.upsystem.api.batch_tracking',
      args: {
        tracking_numbers: trackingNumbers
      }
    });

    if (apiResponse && apiResponse.message && apiResponse.message.success) {
      // 处理API返回的数据，转换为表格格式
      const results = apiResponse.message.data || [];
      
      trackingData = results.map(result => {
        if (result.success && result.data) {
          const item = result.data;
          return {
            trackingNumber: result.tracking_number || '',
            status: item.status || 'unknown',
            deliveryStatus: getStatusInfo(item.status || 'unknown'),
            lastMileTracking: item.last_mile_tracking || '-',
            orderNumber: item.order_number || '-',
            lastEvent: item.last_event || '查询中...',
            route: item.route || 'CN → Unknown',
            trackingHistory: item.tracking_history || [],
            carrierInfo: item.carrier_info || {
              name: '云途物流',
              website: 'https://www.yunexpress.com',
              email: 'service@yunexpress.com',
              phone: '+86 400-123-4567'
            },
            success: true
          };
        } else {
          return {
            trackingNumber: result.tracking_number || '',
            status: 'error',
            deliveryStatus: getStatusInfo('error'),
            lastMileTracking: '-',
            orderNumber: '-',
            lastEvent: result.message || '查询失败',
            route: 'CN → Unknown',
            trackingHistory: [],
            carrierInfo: {
              name: '云途物流',
              website: 'https://www.yunexpress.com',
              email: 'service@yunexpress.com',
              phone: '+86 400-123-4567'
            },
            success: false
          };
        }
      });

      // 显示结果
      showMultipleTrackingResults();
      updateStatusCounts();
      
    } else {
      const errorMsg = apiResponse?.message?.message || '获取跟踪信息失败';
      showError(errorMsg);
    }
  } catch (error) {
    showError('网络错误，请稍后重试: ' + error.message);
  }
}

// 显示多个跟踪结果
function showMultipleTrackingResults() {
  // 隐藏加载和错误状态
  document.getElementById('loadingState').style.display = 'none';
  document.getElementById('errorState').style.display = 'none';
  document.getElementById('emptyState').style.display = 'none';

  // 生成表格行
  generateTrackingTable();

  // 显示结果
  document.getElementById('trackingResults').style.display = 'block';
}

// 生成跟踪表格
function generateTrackingTable() {
  const tbody = document.getElementById('trackingTableBody');
  tbody.innerHTML = '';

  trackingData.forEach((item, itemIndex) => {
    const row = document.createElement('tr');
    row.className = 'flowa-tracking-row';
    row.dataset.status = item.status;
    row.dataset.index = itemIndex;
    
    row.innerHTML = `
      <td>
        <div class="flowa-tracking-number">${item.trackingNumber}</div>
        <div class="flowa-tracking-route">${item.route}</div>
      </td>
      <td>
        <div class="flowa-status-badge ${item.deliveryStatus.class}">
          <span>${item.deliveryStatus.icon}</span>
          <span>${item.deliveryStatus.text}</span>
        </div>
      </td>
      <td>${item.lastMileTracking}</td>
      <td>${item.orderNumber}</td>
      <td>
        <div class="flowa-last-event">${item.lastEvent}</div>
      </td>
    `;

    // 添加点击事件
    row.addEventListener('click', function(e) {
      toggleTrackingDetail(itemIndex);
    });
    
    tbody.appendChild(row);

    // 添加详细信息行
    const detailRow = document.createElement('tr');
    detailRow.className = 'flowa-detail-row';
    detailRow.dataset.index = itemIndex;
    detailRow.innerHTML = `
      <td colspan="5">
        <div class="flowa-detail-content">
          <div class="flowa-timeline-section">
            <h4>跟踪历史</h4>
            <div class="flowa-timeline-container" id="timeline-${itemIndex}">
              <!-- 时间线将通过JavaScript生成 -->
            </div>
          </div>
          <div class="flowa-sidebar-section">
            <h4>包裹信息</h4>
            <div class="flowa-info-row">
              <span class="flowa-info-label">订单号</span>
              <span class="flowa-info-value">${item.orderNumber}</span>
            </div>
            <div class="flowa-info-row">
              <span class="flowa-info-label">运输路线</span>
              <span class="flowa-info-value">${item.route}</span>
            </div>
            <h4>承运商信息</h4>
            <div class="flowa-info-row">
              <span class="flowa-info-label">承运商</span>
              <span class="flowa-info-value">${item.carrierInfo.name || 'Unknown'}</span>
            </div>
            <div class="flowa-info-row">
              <span class="flowa-info-label">官网</span>
              <span class="flowa-info-value">
                ${item.carrierInfo.website ? 
                  `<a href="${item.carrierInfo.website}" target="_blank">${item.carrierInfo.website}</a>` : 
                  'N/A'}
              </span>
            </div>
            <div class="flowa-info-row">
              <span class="flowa-info-label">客服邮箱</span>
              <span class="flowa-info-value">${item.carrierInfo.email || 'N/A'}</span>
            </div>
            <div class="flowa-info-row">
              <span class="flowa-info-label">客服电话</span>
              <span class="flowa-info-value">${item.carrierInfo.phone || 'N/A'}</span>
            </div>
          </div>
        </div>
      </td>
    `;

    tbody.appendChild(detailRow);

    // 生成时间线
    generateTimelineForItem(itemIndex, item.trackingHistory);
  });
}

// 生成单个包裹的时间线
function generateTimelineForItem(itemIndex, historyData) {
  const containerId = 'timeline-' + itemIndex;
  const container = document.getElementById(containerId);
  
  if (!container) {
    return;
  }

  container.innerHTML = '';
  
  if (!historyData || !Array.isArray(historyData)) {
    container.innerHTML = '<p style="color: hsl(var(--muted-foreground)); font-size: 0.875rem;">暂无跟踪历史</p>';
    return;
  }
  
  // 将历史数据倒序排列，最新的事件在最前面
  const reversedHistoryData = [...historyData].reverse();
  
  reversedHistoryData.forEach((item, itemIndex) => {
    const timelineItem = document.createElement('div');
    timelineItem.className = 'flowa-timeline-item';
    
    const formattedTime = formatTimelineTime(item.timestamp);
    
    timelineItem.innerHTML = `
      <div class="flowa-timeline-content">
        <div class="flowa-timeline-time">${formattedTime}</div>
        <div class="flowa-timeline-event">${item.description || item.event}</div>
        ${item.location ? `<div class="flowa-timeline-location">${item.location}</div>` : ''}
      </div>
    `;
    
    container.appendChild(timelineItem);
  });
}

// 切换跟踪详情显示
function toggleTrackingDetail(index) {
  if (index === undefined || index === null || isNaN(index)) {
    return;
  }
  
  const rows = document.querySelectorAll('.flowa-tracking-row');
  const detailRows = document.querySelectorAll('.flowa-detail-row');
  
  // 移除所有选中状态
  rows.forEach(row => row.classList.remove('selected'));
  detailRows.forEach(row => row.classList.remove('expanded'));
  
  // 选中当前行
  const selector = '.flowa-tracking-row[data-index="' + index + '"]';
  const detailSelector = '.flowa-detail-row[data-index="' + index + '"]';
  
  const currentRow = document.querySelector(selector);
  const currentDetail = document.querySelector(detailSelector);
  
  if (currentRow && currentDetail) {
    currentRow.classList.add('selected');
    currentDetail.classList.add('expanded');
  }
}

// 设置活动筛选器
function setActiveFilter(status) {
  const filterTabs = document.querySelectorAll('.flowa-filter-tab');
  filterTabs.forEach(tab => {
    tab.classList.remove('active');
    if (tab.dataset.status === status) {
      tab.classList.add('active');
    }
  });
  currentFilter = status;
}

// 筛选跟踪结果
function filterTrackingResults(status) {
  const rows = document.querySelectorAll('.flowa-tracking-row');
  const detailRows = document.querySelectorAll('.flowa-detail-row');
  
  rows.forEach(row => {
    const rowStatus = row.dataset.status;
    if (status === 'all' || rowStatus === status) {
      row.style.display = '';
      // 同时显示/隐藏对应的详情行
      const index = row.dataset.index;
      const detailRow = document.querySelector('.flowa-detail-row[data-index="' + index + '"]');
      if (detailRow) {
        detailRow.style.display = '';
      }
    } else {
      row.style.display = 'none';
      // 隐藏对应的详情行
      const index = row.dataset.index;
      const detailRow = document.querySelector('.flowa-detail-row[data-index="' + index + '"]');
      if (detailRow) {
        detailRow.style.display = 'none';
      }
    }
  });
}

// 更新状态计数
function updateStatusCounts() {
  const counts = {
    all: trackingData.length,
    processing: 0,
    transit: 0,
    delivered: 0,
    'not-found': 0,
    alert: 0,
    returned: 0
  };

  trackingData.forEach(item => {
    if (counts.hasOwnProperty(item.status)) {
      counts[item.status]++;
    }
  });

  // 更新UI计数
  Object.keys(counts).forEach(status => {
    const element = document.getElementById(status + 'Count');
    if (element) {
      element.textContent = counts[status];
    }
  });
}

// 获取状态信息
function getStatusInfo(status) {
  const statusMap = {
    // 基本包裹状态
    'delivered': { text: '已送达', icon: '✅', class: 'delivered' },
    'in_transit': { text: '运输中', icon: '🚚', class: 'transit' },
    'out_for_delivery': { text: '派送中', icon: '🚛', class: 'transit' },
    'processing': { text: '处理中', icon: '⚙️', class: 'processing' },
    'pending': { text: '待处理', icon: '⏳', class: 'processing' },
    'not-found': { text: '未找到', icon: '❌', class: 'not-found' },
    'exception': { text: '异常', icon: '⚠️', class: 'alert' },
    'returned': { text: '已退回', icon: '🔄', class: 'returned' },
    'unknown': { text: '未知', icon: '❓', class: 'processing' },
    'error': { text: '错误', icon: '❌', class: 'not-found' },
    
    // 轨迹历史状态（中文）
    '订单创建': { text: '订单创建', icon: '📝', class: 'processing' },
    '已取件': { text: '已取件', icon: '📦', class: 'processing' },
    '到达始发地设施': { text: '到达始发地设施', icon: '🏭', class: 'processing' },
    '离开始发地设施': { text: '离开始发地设施', icon: '🚛', class: 'transit' },
    '到达始发机场': { text: '到达始发机场', icon: '✈️', class: 'transit' },
    '国际航班起飞': { text: '国际航班起飞', icon: '✈️', class: 'transit' },
    '清关处理中': { text: '清关处理中', icon: '🏛️', class: 'processing' },
    '国际航班到达': { text: '国际航班到达', icon: '✈️', class: 'transit' },
    '清关完成': { text: '清关完成', icon: '✅', class: 'processing' },
    '运输中': { text: '运输中', icon: '🚚', class: 'transit' },
    '到达中转站': { text: '到达中转站', icon: '🏢', class: 'transit' },
    '承运商运输中': { text: '承运商运输中', icon: '🚛', class: 'transit' },
    '派送中': { text: '派送中', icon: '🚚', class: 'transit' },
    '已送达': { text: '已送达', icon: '✅', class: 'delivered' },
    '异常': { text: '异常', icon: '⚠️', class: 'alert' },
    '已退回': { text: '已退回', icon: '🔄', class: 'returned' }
  };
  
  return statusMap[status] || { text: status, icon: '❓', class: 'processing' };
}

// 格式化时间线时间
function formatTimelineTime(timestamp) {
  if (!timestamp) return 'Unknown time';
  
  const date = new Date(timestamp);
  const options = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    timeZone: 'Asia/Shanghai'
  };
  
  return date.toLocaleString('zh-CN', options);
}

// 显示加载状态
function showLoading() {
  document.getElementById('trackingResults').style.display = 'none';
  document.getElementById('errorState').style.display = 'none';
  document.getElementById('emptyState').style.display = 'none';
  document.getElementById('loadingState').style.display = 'block';
}

// 显示错误信息
function showError(message) {
  console.log('显示错误信息:', message);
  
  let errorText = message;
  if (typeof message === 'object') {
    errorText = JSON.stringify(message, null, 2);
  }
  
  document.getElementById('trackingResults').style.display = 'none';
  document.getElementById('loadingState').style.display = 'none';
  document.getElementById('emptyState').style.display = 'none';
  document.getElementById('errorState').style.display = 'block';
  document.getElementById('errorMessage').textContent = errorText;
}
</script>
{% endblock %}
